package net.myjung.workbench;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StringUtils;

public class ReadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public ReadFileServlet() {
		super();
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (!ServletFileUpload.isMultipartContent(request))
			throw new ServletException("invalidAccess");
		
		ServletFileUpload upload = new ServletFileUpload();
		upload.setHeaderEncoding("UTF-8");
		upload.setSizeMax(1024000);
		upload.setFileSizeMax(1024000);
		response.setContentType("text/plain;charset=UTF-8");

//		try {
//			upload.setFileItemFactory(new DiskFileItemFactory());
//			List items = upload.parseRequest(request);
//			for (Object obj : items) {
//				FileItem item = (FileItem) obj;
//				if (item.isFormField()) {
//					
//				} else {
//					String data = item.getString("MS949");
//					response.getOutputStream().write(data.getBytes("UTF-8"));
//					break;
//				}
//			}
//		} catch (Exception e) {
//			throw new ServletException(e);
//		}
		
		OutputStream os = null;
		InputStream is = null;
		try {
			FileItemIterator itr = upload.getItemIterator(request);
			os = response.getOutputStream();
			while (itr.hasNext()) {
				FileItemStream item = itr.next();
				if (item.isFormField())
					continue;
				
				is = item.openStream();
				String data = StringUtils.replace(IOUtils.toString(is, "MS949"), "\r\n", "\n");
				is = IOUtils.toInputStream(data, "UTF-8");
				int len;
				byte[] buffer = new byte[10240];
				while ((len = is.read(buffer, 0, buffer.length)) != -1) {
					os.write(buffer, 0, len);
				}
//				os.write(data.getBytes("UTF-8"));
				
				break;
			}
		} catch (Exception e) {
			throw new ServletException(e);
		} finally {
			if (is != null)
				is.close();
			if (os != null) {
				os.flush();
				os.close();
			}
		}
	}
}
